package com.xchb.im.conne.server.netty;

import com.alibaba.fastjson.JSONObject;


import com.xchb.im.conne.pojo.LoginInfo;
import com.xchb.im.conne.utils.SpringUtil;
import com.xchb.im.conne.utils.UserConnectionHolder;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 
 * @Description: 处理消息的handler
 * TextWebSocketFrame： 在netty中，是用于为websocket专门处理文本的对象，frame是消息的载体
 */
@Slf4j
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	private UserConnectionHolder userConnectionHolder = SpringUtil.getBean(UserConnectionHolder.class);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) 
			throws Exception {
		String text = msg.text();
		log.info("收到消息：{}",text);
		LoginInfo loginInfo = JSONObject.parseObject(text, LoginInfo.class);
		if(loginInfo!=null && StrUtil.isNotBlank(loginInfo.getUserId())){
			//绑定关系
			userConnectionHolder.login(loginInfo.getUserId(),ctx.channel());
			log.info("连接成功：{}",loginInfo.getUserId());
		}

	}
	

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

		this.close(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		this.close(ctx);
	}

	private void close(ChannelHandlerContext ctx){
		String channelId = ctx.channel().id().asShortText();
		ctx.channel().close();
		userConnectionHolder.loginout(channelId);
		log.info("客户端被移除，channelId为：" + channelId);
	}
}
